-module(t_chord).
-include("db.hrl").

-compile(export_all).

test_succs(Node) ->
    Result = test_rec(Node,Node,[] ),
    io:format("Results: ~p~n", [Result]).

test_rec(FirstNode, CurrentNode, Acc) ->
    case (FirstNode == CurrentNode) and (length(Acc) > 0) of
        true  -> Acc;
        false -> Suc = call(CurrentNode, {get_successor}),
                 SucPred = call(Suc#node.node, {get_predecessor}),
                 Pred = call (CurrentNode, {get_predecessor}),
                 PredSuc = call (Pred#node.node, {get_successor}),
                 SucOK = case SucPred#node.node == CurrentNode of
                             true -> "SucPred ok";
                             false -> "SucPred Error: ("++ atom_to_list(SucPred#node.node) 
                         end,
                 PredOK = case PredSuc#node.node == CurrentNode of
                             true -> "PredSuc ok";
                             false -> "PredSuc Error: ("++ atom_to_list(SucPred#node.node) 
                         end,
                 test_rec(FirstNode, Suc#node.node, Acc ++ [{CurrentNode,SucOK,PredOK}])
    end.

%% /////////////////////////////////////////////////////////

test_fingers(Node) ->
    Result = test_fingers_loop(Node, Node, []),
    io:format("Results: ~p~n", [Result]).

test_fingers_loop(FirstNode, CurrentNode, Acc) ->
    case (FirstNode == CurrentNode) and (length(Acc) > 0) of
        true  -> Acc;
        false ->
            Suc = call(CurrentNode, {get_successor}),
            Ft = call(CurrentNode, {get_finger_table}),
            NodeRes = test_finger_table(CurrentNode, Ft),
            NodeOk = case NodeRes of
                true -> "Finger table ok for node";
                false -> "Finger table wrong for node"
            end,
            test_fingers_loop(FirstNode, Suc#node.node, Acc + [{CurrentNode, NodeOk}])
    end.

test_finger_table(Node, Ft) ->
    test_finger_table_loop(Node, Ft, []).

test_finger_table_loop(_Node, [], Acc) -> Acc;
test_finger_table_loop(Node, [_FtEntry|Ft], Acc) ->
    Res = ok,
    test_finger_table_loop(Node, Ft, Acc + [Res]).

call(Node, Msg) ->
    gen_server:call({dht,Node}, Msg).

